package com.test.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.test.clyq.entity.Users;

public class SessionUtil {

	/** 当前登陆用户所在网站 */
	public static final String CURRENTWEBSITE_KEY = "currwebsite";

	/** 当前登陆用户的session保存的键 */
	public static final String USERSESSION_KEY = "user";

	/**
	 * 销毁当前session
	 * 
	 * @param request
	 *            当前请求
	 */
	public static void destroySession(HttpServletRequest request) {
		if (request == null) {
			return;
		}
		HttpSession session = request.getSession();
		session.invalidate();
	}

	/**
	 * 使用当前请求获取当前登陆用户所在网站
	 * 
	 * @param request
	 *            当前请求
	 * @return Long 站点id
	 */
	public static Long getCurrentWebsiteFromSession(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		HttpSession session = request.getSession();
		return (Long) session.getAttribute(SessionUtil.CURRENTWEBSITE_KEY);
	}

	/**
	 * 使用当前请求获取当前登陆用户
	 * 
	 * @param request
	 *            当前请求
	 * @return NLUsers 当前登陆用户
	 */
	public static Users getUserFromSession(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		HttpSession session = request.getSession();
		return (Users) session.getAttribute(SessionUtil.USERSESSION_KEY);
	}
	
	
	/**
	 * 获取SessionKey
	 * 
	 * @param request
	 *            当前请求
	 * @return SessionKey SessionKey
	 */
	public static String getKey2Session(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		HttpSession session = request.getSession();
		return (String) session.getAttribute("taoBaoSessionKey");
	}
	

	/**
	 * 站点更替
	 */
	public static void setCurrentWebsite(HttpServletRequest request, Long websiteId) {
		if (request == null) {
			return;
		}
		HttpSession session = request.getSession();
		Users users = (Users) session.getAttribute(SessionUtil.USERSESSION_KEY);
		session.setAttribute(SessionUtil.USERSESSION_KEY, users);
		session.setAttribute(SessionUtil.CURRENTWEBSITE_KEY, websiteId);
	}

	/**
	 * 保存当前session
	 * 
	 * @param request
	 *            当前请求
	 * @param user
	 *            当前用户
	 */
	public static void setSession(HttpServletRequest request, Users user) {
		if (request == null || user == null) {
			return;
		}
		HttpSession session = request.getSession();
		session.setAttribute(SessionUtil.USERSESSION_KEY, user);
		// session.setAttribute(SessionUtil.CURRENTWEBSITE_KEY,
		// user.getUsersWebsiteId());
	}
}
